介绍
:nth-child(n) | p:nth-child(2) | 选择属于其父元素的第二个子元素的每个<p>标签 |
:nth-last-child(n) | p:nth-last-child(2) | 同上,从最后一个元素开始计数 |
:nth-of-type(n) | p:nth-of-type(2) | 选择属于其父元素的第二个<p>元素的每个<p>元素 |
:nth-last-of-type(n) | p:nth-last-of-type(2) | 同上,但是从最后一个元素开始计数 |
我们通常不会在标签后面,而是 .class后加上这类选择器,但是有时候无法得到我们想要的效果。
.class:nth-child(n) 会直接在 .class 的父元素中找,如果第n个子元素是 .class 属性,则匹配成功。
.class:nth-of-type(n) 会先判断 .class 是什么标签,再在父元素中查找该标签,如果第n个该标签的元素是 .class 属性,则匹配成功。
<body>
<div class="wrap" style="display:flex;flex-direction:column;">
<h4 class="item1">test</h4>
<span class="item1">第一个span<span>--------第一个span的子span</span></span>
<span class="item2">第二个span</span>
<span class="item2">第三个span</span>
</div>
</body>
test1
这个比较好理解,div的父元素是body,body第一个子元素,如果是div,则匹配
div:nth-child(1){
color: #ff9900;
}
test2
这里第一个span没有变色,是因为span的父元素div的第一个子元素不是span而是h4,无法匹配。
span:nth-child(1){
color: #ff9900;
}
test3
如果你希望wrap第一个span变色,需要使用 :nth-of-type,它只会计算该类型的元素。span的父元素div中所有的span子元素中的第一个匹配。
span:nth-of-type(1) {
color:red;
}
test4
如果使用 .class,下面写法会匹配 .item 父元素div中的第一个元素。
.item1:nth-child(1) {
color: #ff9900;
}
test5
先查找item1所属标签 是h4和span,再匹配父元素div中第一个h4,和第一个span,都是 .item1。
.item1:nth-of-type(1) {
color:red;
}
test6
先查找item1所属标签 h4和span,再查找父元素div中第二个h4,和第二个span,h4没有第二个,第二个span不是 item1,都无法匹配
.item1:nth-of-type(2) {
color:red;
}
test7
先查找item2所属标签为span,再查找父元素div中第二个span,检查它是不是 item2,是则匹配成功。但是和我们想象中不一样,我们更希望是第二个item2,也就是第三个item为红色。
.item2:nth-of-type(2) {
color:red;
}
总结
使用这类选择器时经常会得到和我们想象中不同的结果,需要多注意。